#include "bilateralaudioplay.h"
#include <QDebug>
#include <QThread>
#include "utils/signalcenter.h"
bilateralAudioPlay::bilateralAudioPlay(QObject *parent)
    : QObject{parent}
    , MediaDevices(new QMediaDevices(this))
    , mircrPhoneIODevice(new MircrophoneIODevice(this))
    , outPutVolume(0.5)
{
    defalutOutputAudioDevice = MediaDevices->defaultAudioOutput();
    intputAudioDevices = MediaDevices->audioInputs();
    connect(&SignalCenter::instance(),
            &SignalCenter::intputAudioVolumeChange,
            this,
            &bilateralAudioPlay::onIntputAudioVolumeChange);
}

QVector<QString> bilateralAudioPlay::getIntputDevicesDescription()
{
    for (auto &intputDevice : intputAudioDevices) {
        intputDevicesDescription.emplace_back(intputDevice.description());
    }
    return intputDevicesDescription;
}

void bilateralAudioPlay::selectInputAudioDevice(int index)
{
    if (index > intputAudioDevices.size()) {
        qWarning() << "index 超出输出设备的个数";
        return;
    }

    selectIntputAudioDevice = intputAudioDevices[index];
    format = defalutOutputAudioDevice.preferredFormat();
    if (!selectIntputAudioDevice.isFormatSupported(format)) {
        qWarning() << "output format not supported";
        return;
    }

    qDebug() << "format.sampleRate: " << format.sampleRate()
             << "format.channelCount: " << format.channelCount()
             << "format.sampleFormat: " << format.sampleFormat();
}

void bilateralAudioPlay::start()
{
    mircrPhoneIODevice->start();

    //初始化输入源
    audioSource = new QAudioSource(selectIntputAudioDevice, format, this);

    // 将麦克风捕获的数据写入到 mircrPhoneIODevice 中
    audioSource->start(mircrPhoneIODevice);
    QByteArray dummyAudioData(1024, '\0');
    mircrPhoneIODevice->write(dummyAudioData.data(), dummyAudioData.size());
    // //初始化输出源
    audioSinkOutput = new QAudioSink(defalutOutputAudioDevice, format, this);
    audioSinkOutput->setVolume(outPutVolume);
    //将自定义的IO设备绑定到 audioSinkOutput设备的输出源上，
    audioSinkOutput->start(mircrPhoneIODevice);
    qDebug() << "QAudioSink buffer size:" << audioSinkOutput->bufferSize();
    qDebug() << "QAudioSink state:" << audioSinkOutput->state();
}

void bilateralAudioPlay::stop()
{
    mircrPhoneIODevice->stop();
    audioSource->stop();
    audioSinkOutput->stop();
}

void bilateralAudioPlay::onIntputAudioVolumeChange(float volume)
{
    if (!audioSinkOutput) {
        outPutVolume = volume;
    } else {
        qDebug() << volume;
        audioSinkOutput->setVolume(volume);
    }
}
